package com.mdd.admin.service.sign.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.DefaultAlipayClient;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mdd.admin.service.bill.OrderBillInfoService;
import com.mdd.admin.service.order.IOrderLeaseDetailsService;
import com.mdd.admin.service.sign.AlipaySignUserAgreementRecordService;
import com.mdd.admin.vo.order.OrderLeaseDetailVo;
import com.mdd.common.entity.OrderFlowInfo;
import com.mdd.common.entity.agreement.AlipaySignUserAgreementRecord;
import com.mdd.common.entity.order.OrderInfo;
import com.mdd.common.entity.user.UserAuth;
import com.mdd.common.enums.OrderEnum;
import com.mdd.common.enums.auth.AuthStatusEnum;
import com.mdd.common.enums.order.status.RentOrderStatusEnum;
import com.mdd.common.enums.order.type.OrderFlowTypeEnum;
import com.mdd.common.mapper.OrderFlowInfoMapper;
import com.mdd.common.mapper.order.OrderInfoMapper;
import com.mdd.common.mapper.sign.AlipaySignUserAgreementRecordMapper;
import com.mdd.common.mapper.user.UserAuthMapper;
import com.mdd.common.util.CodeUtils;
import com.mdd.common.util.TimeUtils;
import com.mdd.service.agreement.UserAgreementService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

/**
* @author DELL
* @description 针对表【alipay_sign_user_agreement_record(授权记录)】的数据库操作Service实现
* @createDate 2023-11-01 17:23:12
*/
@Service
public class AlipaySignUserAgreementRecordServiceImpl extends ServiceImpl<AlipaySignUserAgreementRecordMapper, AlipaySignUserAgreementRecord>
    implements AlipaySignUserAgreementRecordService {

    @Resource
    OrderBillInfoService orderBillInfoService;
    @Resource
    OrderInfoMapper orderInfoMapper;
    @Resource
    UserAuthMapper userAuthMapper;
    @Resource
    IOrderLeaseDetailsService orderLeaseDetailsService;
    @Resource
    UserAgreementService userAgreementService;
    @Resource
    DefaultAlipayClient defaultAlipayClient;
    @Resource
    OrderFlowInfoMapper orderFlowInfoMapper;
    @Override
    public AlipaySignUserAgreementRecord getRecordByOrderId(String orderId) {
        LambdaQueryWrapper<AlipaySignUserAgreementRecord> agreementRecordWrapper=new LambdaQueryWrapper<>();
        agreementRecordWrapper.eq(AlipaySignUserAgreementRecord::getOrderId,orderId)
                .eq(AlipaySignUserAgreementRecord::getStatus, AuthStatusEnum.AUTHORIZATION_SUCCESSFUL.getCode());
        return this.getOne(agreementRecordWrapper);
    }
    @Override
    public AlipaySignUserAgreementRecord getRecordByUserId(Long userId) {
        LambdaQueryWrapper<AlipaySignUserAgreementRecord> agreementRecordWrapper=new LambdaQueryWrapper<>();
        agreementRecordWrapper.eq(AlipaySignUserAgreementRecord::getUserId,userId)
                .eq(AlipaySignUserAgreementRecord::getStatus, AuthStatusEnum.AUTHORIZATION_SUCCESSFUL.getCode());
        return this.getOne(agreementRecordWrapper);
    }

    @Override
    public AlipaySignUserAgreementRecord getRecordByAgreementNo(String agreementNo) {
        LambdaQueryWrapper<AlipaySignUserAgreementRecord> agreementRecordWrapper=new LambdaQueryWrapper<>();
        agreementRecordWrapper.eq(AlipaySignUserAgreementRecord::getAgreementNo,agreementNo)
                .eq(AlipaySignUserAgreementRecord::getStatus, AuthStatusEnum.AUTHORIZATION_SUCCESSFUL.getCode());
        return this.getOne(agreementRecordWrapper);
    }
    @Transactional
    @Override
    public AlipaySignUserAgreementRecord  updateRecordByAlipayUserId(String alipayUserId,String agreementNo) {
        UserAuth userAuth = userAuthMapper.selectOne(new LambdaQueryWrapper<UserAuth>().eq(UserAuth::getAlipayUserid,alipayUserId).last("limit 1"));
        LambdaQueryWrapper<AlipaySignUserAgreementRecord> agreementRecordWrapper=new LambdaQueryWrapper<>();
        agreementRecordWrapper.eq(AlipaySignUserAgreementRecord::getUserId,userAuth.getUserId())
                .eq(AlipaySignUserAgreementRecord::getStatus, AuthStatusEnum.TO_BE_AUTHORIZED.getCode());
        AlipaySignUserAgreementRecord agreementRecord =  this.getOne(agreementRecordWrapper);
        agreementRecord.setAgreementNo(agreementNo);
        this.updateById(agreementRecord);
        return agreementRecord;
    }
    @Transactional
    @Override
    public AlipaySignUserAgreementRecord cancelRecordByAlipayUserId(String agreementNo) {
        AlipaySignUserAgreementRecord agreementRecord =  this.getRecordByAgreementNo(agreementNo);
        if(Objects.nonNull(agreementRecord)) {
            agreementRecord.setStatus(AuthStatusEnum.AUTHORIZATION_CANCELLATION.getCode());
            this.updateById(agreementRecord);
        }
        return agreementRecord;
    }
    @Transactional
    @Override
    public AlipaySignUserAgreementRecord cancelRecordByOrderId(Long orderId) throws AlipayApiException {
        AlipaySignUserAgreementRecord agreementRecord =  this.getRecordByOrderId(orderId.toString());
        if(Objects.nonNull(agreementRecord)&& agreementRecord.getStatus().equals(1)){
            saveFlowInfoLog(agreementRecord.getOrderId(), OrderFlowTypeEnum.CANCEL_AGREEMENT_RECORD_SIGN, null);
            JSONObject bizContent = new JSONObject();
            bizContent.put("agreement_no", agreementRecord.getAgreementNo());
            bizContent.put("operate_type","confirm");
            agreementRecord.setStatus(AuthStatusEnum.AUTHORIZATION_CANCELLATION.getCode());
            this.updateById(agreementRecord);
            //取消授权
            userAgreementService.userAgreementUnsign(defaultAlipayClient,bizContent);
        }
        return agreementRecord;
    }
    @Override
    @Transactional
    public AlipaySignUserAgreementRecord applyCancelRecordByAlipayUserId(String agreementNo) throws AlipayApiException {
        AlipaySignUserAgreementRecord agreementRecord =  this.getRecordByAgreementNo(agreementNo);

        OrderInfo orderInfo = orderInfoMapper.selectById(agreementRecord.getOrderId());
        if(Objects.nonNull(agreementRecord)&& agreementRecord.getStatus().equals(1)){
            saveFlowInfoLog(agreementRecord.getOrderId(), OrderFlowTypeEnum.CANCEL_AGREEMENT_RECORD_SIGN, null);

            JSONObject bizContent = new JSONObject();
            bizContent.put("agreement_no", agreementRecord.getAgreementNo());
            //订单状态： 3待提车4租赁中5待结算  拒绝取消 (车辆准备中 临时)
            if(OrderEnum.PREPARATION_ORDER.getCode().equals(orderInfo.getStatus())||
                    OrderEnum.VEHICLE_DELIVERED_ORDER.getCode().equals(orderInfo.getStatus())
                    ||OrderEnum.UNDER_WAY.getCode().equals(orderInfo.getStatus())
                    || OrderEnum.UN_SETTLE_ORDER.getCode().equals(orderInfo.getStatus())){
                bizContent.put("operate_type","invalid");
                JSONObject extendParams = new JSONObject();
                extendParams.put("UNSIGN_ERROR_CODE","USER_IN_SERVICE");
                bizContent.put("extend_params",  extendParams);
            }else {
                bizContent.put("operate_type","confirm");
                agreementRecord.setStatus(AuthStatusEnum.AUTHORIZATION_CANCELLATION.getCode());
                this.updateById(agreementRecord);
             }
            //取消授权
            userAgreementService.userAgreementUnsign(defaultAlipayClient,bizContent);
        }
        return agreementRecord;
    }
    @Transactional
    @Override
    public void finalSign(AlipaySignUserAgreementRecord alipaySignUserAgreementRecord) {
        alipaySignUserAgreementRecord.setStatus(AuthStatusEnum.AUTHORIZATION_SUCCESSFUL.getCode());
        this.updateById(alipaySignUserAgreementRecord);
        //创建账单
        OrderInfo orderInfo = orderInfoMapper.selectById(alipaySignUserAgreementRecord.getOrderId());
        OrderLeaseDetailVo orderLeaseDetailVo = orderLeaseDetailsService.getOrderLeaseByOrderId(orderInfo.getId());
        orderBillInfoService.createBillInfo(orderInfo.getId(),orderInfo.getDeptId(),orderInfo.getUserId(),orderLeaseDetailVo.getEachIssue(),orderLeaseDetailVo.getLeasePeriod());
        orderInfo.setStatus(RentOrderStatusEnum.READING_CAR.getCode());
        orderInfo.setPaymentTime(TimeUtils.nowDate());
        orderInfoMapper.updateById(orderInfo);
    }


    /**
     * 流水日志
     * @param orderId
     * @param orderFlowTypeEnum
     * @param amount
     * @return
     */

    private OrderFlowInfo saveFlowInfoLog(Long orderId , OrderFlowTypeEnum orderFlowTypeEnum, BigDecimal amount){
        OrderFlowInfo orderFlowInfo =   new OrderFlowInfo();
        orderFlowInfo.setFlowNo(CodeUtils.getFlowNo(orderFlowTypeEnum));
        orderFlowInfo.setAmount(amount);
        orderFlowInfo.setOrderid(orderId);
        orderFlowInfo.setType(orderFlowTypeEnum.getCode());
        orderFlowInfo.setItemName(orderFlowTypeEnum.getMsg());
        orderFlowInfo.setSourceAppId(0);
        orderFlowInfoMapper.insert(orderFlowInfo);
        return orderFlowInfo;
    }
}




